package com.yu.dv.strategy;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 抽象策略工厂
 */
public abstract class AbstractStrategyFactory<T> implements StrategyFactory<T> {

    protected final Map<String, T> strategies = new ConcurrentHashMap<>();
    protected final String factoryName;

    protected AbstractStrategyFactory(String factoryName) {
        this.factoryName = factoryName;
    }

    @Override
    public T getStrategy(String key) {
        if (key == null) {
            return getDefaultStrategy();
        }
        return strategies.get(key.toLowerCase());
    }

    @Override
    public Map<String, T> getAllStrategies() {
        return new ConcurrentHashMap<>(strategies);
    }

    @Override
    public void registerStrategy(String key, T strategy) {
        if (key != null && strategy != null) {
            strategies.put(key.toLowerCase(), strategy);
        }
    }

    @Override
    public void unregisterStrategy(String key) {
        if (key != null) {
            strategies.remove(key.toLowerCase());
        }
    }

    @Override
    public String getFactoryName() {
        return factoryName;
    }

    /**
     * 获取默认策略（子类可重写）
     */
    protected  T getDefaultStrategy() {
        return null;
    }

    /**
     * 工厂初始化方法
     */
    public abstract void initialize();
}